package com.trackmybudget.mvc;

import java.util.Map;

import javax.validation.Valid;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.trackmybudget.domain.Contact;
import com.trackmybudget.service.ContactService;

@Controller
public class ContactController {
  
  private final static String CLASS_NAME = "ContactController";
  
  private static final Logger LOGGER = Logger.getLogger(ContactController.class.getName());

	@Autowired
	private ContactService contactService;

	@RequestMapping("/contact")
	public String listContacts(Map<String, Object> map) {
	  final String METHOD_NAME = ".listContacts";
	  if (LOGGER.getLevel() == Level.DEBUG) {
	    LOGGER.debug("Entered: " + CLASS_NAME + METHOD_NAME);
	  }
	  
		map.put("contact", new Contact());
		map.put("contactList", contactService.listContact());
		
    if (LOGGER.getLevel() == Level.DEBUG) {
      LOGGER.debug("Exited: " + CLASS_NAME + METHOD_NAME);
    }

		return "contact";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String addContact(@ModelAttribute("contact") @Valid Contact contact,
			BindingResult result, Map<String, Object> map) {
	  LOGGER.debug("Adding contacts...");
	  
	  String returnVal = null;
	  if (!result.hasErrors()) {
		  contactService.addContact(contact);
		  returnVal = "redirect:/contact";
	  } else {
	    map.put("contactList", contactService.listContact());
	    returnVal = "/contact";
	  }

		return returnVal;
	}

	@RequestMapping("/delete/{contactId}")
	public String deleteContact(@PathVariable("contactId") Integer contactId) {
		contactService.removeContact(contactId);

		return "redirect:/contact";
	}
}
